package com.example.gameforum.controller;

import com.example.gameforum.entity.Post;
import com.example.gameforum.entity.User;
import com.example.gameforum.service.PostService;
import com.example.gameforum.service.UserService;
import com.example.gameforum.utils.CommunityUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {


    @Autowired
    private UserService userService;

    @Autowired
    private PostService postService;


    @RequestMapping("/login")
    public String login(HttpServletRequest request,
                        int loginid, String loginpassword){
        HttpSession session = request.getSession();
        User user=userService.getById(loginid);
        if (user.getPassword().equals(loginpassword)){
            session.setAttribute("user",user);
            List<Post> posts=postService.getAllPost();
            session.setAttribute("posts",posts);
            return "home";
        }
        return "index";
    }

    @RequestMapping("/registerpage")
    public String getRegisterPage(){
        return "register";
    }

    @RequestMapping("/register")
    public String register(HttpServletRequest request,
                            String pass){
        HttpSession session = request.getSession();
        User user=new User();
        int id= CommunityUtils.getRandomEightId();
        user.setAddress("挪威");
        user.setId(id);
        user.setName("xiaojun");
        user.setSignatrue("why sky blue");
        user.setPassword(pass);
        String url="images/"+CommunityUtils.getRandomOneNum()+".gif";
        user.setPicurl(url);
        userService.insertUser(user);
        session.setAttribute("user",user);
        List<Post> posts=postService.getAllPost();
        session.setAttribute("posts",posts);
        return "home";
    }
}
